<template>
  <dialog-editor ref="dialog"></dialog-editor>
</template>

<script>
import DialogEditor from '@/components/DialogEditor'
import dialogMixins from '@/utils/commonDialogMixins'
import {mRequest} from '@/utils/request'
import {treeDataTranslate} from '@/utils'

export default {
  mixins: [dialogMixins],
  components: {DialogEditor},
  data() {
    return {
      dataFormConfig: {
        roleId: {
          hidden: true
        },
        roleName: {
          label: '角色名称',
          placeholder: '请输入角色名称'
        },
        remark: {
          inputType: 'textarea',
          label: '备注',
          placeholder: '请输入备注'
        },
        menuIdList: {
          label: '授权',
          type: 'tree',
          treeItemList: [],
          treeLabelAttr: 'name',
          treeChildrenAttr: 'children',
          nodeKey: 'menuId',
          beforeSubmitFunc: this.beforeSubmit,
          dataLoadedFunc: this.dataLoaded,
          default: []
        }
      },
      tempKey: -666666
    }
  },
  methods: {
    initMenuList() {
      mRequest('systemApi/listMenu', {}, ({data}) => {
        this.dataFormConfig.menuIdList.treeItemList = treeDataTranslate(data, 'menuId')
      })
    },
    init(id) {
      this.dataForm.roleId = id || 0
      this.initMenuList()

      this.$refs.dialog.initDialog({
        dataForm: this.dataForm,
        config: this.dataFormConfig,
        dataRule: this.getNeedDataRule('roleName'),
        initApi: 'systemApi/roleInfo',
        saveApi: 'systemApi/saveRole',
        updateApi: 'systemApi/updateRole',
        objectName: 'role',
        idAttr: 'roleId'
      })
    },
    beforeSubmit(vm) {
      this.dataForm.menuIdList = [].concat(vm.$refs.tree.getCheckedKeys(), [this.tempKey], vm.$refs.tree.getHalfCheckedKeys())
    },
    dataLoaded(vm) {
      const itemList = this.dataForm.menuIdList
      const idx = itemList.indexOf(this.tempKey)

      if (idx !== -1) {
        itemList.splice(idx, itemList.length - idx)
      }
      vm.$refs.tree.setCheckedKeys(itemList)
    }
  }
}
</script>

<style>

</style>
